// internal/apps/auth/view/user_repository.go
package repositories

import (
	"star-go-app/internal/apps/auth/models"
	"star-go-app/pkg/infra/database"

	"gorm.io/gorm"
)

type UserRepository interface {
	Create(user *models.User) error
	GetByID(id uint64) (*models.User, error)
	GetByUsername(username string) (*models.User, error)
	GetByEmail(email string) (*models.User, error)
	GetList(offset, limit int) ([]*models.User, int64, error)
	Update(user *models.User) error
	UpdateFields(id uint64, fields map[string]interface{}) error
	Delete(id uint64) error
	DeletePermanently(id uint64) error
	Exists(id uint64) bool
}

type userRepository struct {
	db *gorm.DB
}

func NewUserRepository() UserRepository {
	return &userRepository{
		db: database.GetDB(),
	}
}

// Create 创建用户
func (r *userRepository) Create(user *models.User) error {
	return r.db.Create(user).Error
}

// GetByID 根据ID获取用户
func (r *userRepository) GetByID(id uint64) (*models.User, error) {
	var user models.User
	err := r.db.Preload("Role").First(&user, id).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// GetByUsername 根据用户名获取用户
func (r *userRepository) GetByUsername(username string) (*models.User, error) {
	var user models.User
	err := r.db.Preload("Role").Where("username = ?", username).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// GetByEmail 根据邮箱获取用户
func (r *userRepository) GetByEmail(email string) (*models.User, error) {
	var user models.User
	err := r.db.Preload("Role").Where("email = ?", email).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// GetList 获取用户列表
func (r *userRepository) GetList(offset, limit int) ([]*models.User, int64, error) {
	var users []*models.User
	var total int64

	// 获取总数
	if err := r.db.Model(&models.User{}).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	err := r.db.Preload("Role").Offset(offset).Limit(limit).Find(&users).Error
	if err != nil {
		return nil, 0, err
	}

	return users, total, nil
}

// Update 更新用户（全量更新）
func (r *userRepository) Update(user *models.User) error {
	return r.db.Save(user).Error
}

// UpdateFields 更新用户指定字段（部分更新）
func (r *userRepository) UpdateFields(id uint64, fields map[string]interface{}) error {
	return r.db.Model(&models.User{}).Where("id = ?", id).Updates(fields).Error
}

// Delete 软删除用户
func (r *userRepository) Delete(id uint64) error {
	return r.db.Delete(&models.User{}, id).Error
}

// DeletePermanently 永久删除用户
func (r *userRepository) DeletePermanently(id uint64) error {
	return r.db.Unscoped().Delete(&models.User{}, id).Error
}

// Exists 检查用户是否存在
func (r *userRepository) Exists(id uint64) bool {
	var count int64
	r.db.Model(&models.User{}).Where("id = ?", id).Count(&count)
	return count > 0
}
